# -*- coding: utf-8 -*-
import pendulum
from datetime import timedelta
from utils.operators.cluster_for_spark_sql_operator import SparkSqlOperator
from airflow.exceptions import AirflowSkipException
from spmi.time_sensor.time_after_08_00 import time_after_08_00

cst = pendulum.timezone('Asia/Shanghai')
class BranchRichSqlSensor(SparkSqlOperator):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['01', '17']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)



#Hive表名
hive_table = "dm_spmi_enter_port_weight_range_rate_month"
#任务名
task_id = f"spmi_dm__{hive_table}"

spmi_dm__dm_spmi_enter_port_weight_range_rate_month = BranchRichSqlSensor(
    task_id=f'{task_id}',
    task_concurrency=1,
    pool_slots=2,
    master='yarn',
    name=f'{task_id}_{{{{ execution_date | date_add(1) | cst_ds }}}}',
    sql=f'spmi/dm/spmi/{hive_table}/execute.sql',
    retries=0,
    email=['matthew.xiong@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    driver_memory='4G',
    driver_cores=2,
    executor_cores=4,
    executor_memory='12G',
    num_executors=50,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.dynamicAllocation.enabled': 'true',  # 动态资源开启
          'spark.shuffle.service.enabled': 'true',  # 动态资源 Shuffle 服务开启
          'spark.dynamicAllocation.maxExecutors': 100,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 600,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode': 'dynamic',  # 允许删改已存在的分区
          'spark.executor.memoryOverhead': '4G',  # 堆外内存
          'spark.shuffle.consolidateFiles': 'true',
          'spark.sql.shuffle.partitions': 1000,
          'spark.sql.autoBroadcastJoinThreshold': 104857600
          },
    hiveconf={'hive.exec.dynamic.partition': 'true',  # 动态分区
              'hive.exec.dynamic.partition.mode': 'nonstrict',
              'hive.exec.max.dynamic.partitions': 100,
              'hive.exec.max.dynamic.partitions.pernode': 100,
              },
)

spmi_dm__dm_spmi_enter_port_weight_range_rate_month << time_after_08_00
